<template>
 <div class="borrower">
      
      <el-card class="box-card" shadow="never" style="border:0px;">
        <el-button style="float:right;margin-right:18%;" type="primary" size="mini" v-if="defaultChangeValue!='detail'" @click="createHouseDraft(2)" >保存草稿</el-button>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="right" label-width="110px" style="width: 600px; margin-left:50px;">

          <el-form-item label="产证号" prop="licenseNo" :rules="{required: true,message: '请输入产证号',trigger: 'blur'}">
          <el-input type="textarea" rows="2"  v-model="dataForm.licenseNo" @input="vailInput('licenseNo')"/>
        </el-form-item>
         <el-form-item label="抵押物用途" prop="purpose" :rules="{ required: false,message: '请选择抵押物用途',trigger: 'change'}">
          <DicSelect dictType = "抵押物用途" :dictValue="dataForm.purpose" v-on:dictValue="dataForm.purpose = $event"/>
        </el-form-item>
         <el-form-item label="共有情况" prop="ownedSituation" :rules="{ required: false,message: '请选择共有情况',trigger: 'change'}">
          <DicSelect dictType = "共有情况" :dictValue="dataForm.ownedSituation" v-on:dictValue="dataForm.ownedSituation = $event"/>
        </el-form-item>
         <el-form-item label="获取方式" prop="accessType" :rules="{required: false,message: '请输入获取方式',trigger: 'change'}">
          <DicSelect dictType = "获取方式" :dictValue="dataForm.accessType" v-on:dictValue="dataForm.accessType = $event"/>
        </el-form-item>
        <el-form-item label="房屋地址" prop="areaId" :rules="{required: false,message: '请输入房屋地址',trigger: 'change'}">
           <el-cascader v-model="regionValues" @change="handleChangeRegion" :options="regionList" clearable  placeholder="请选择区域" :props="{ expandTrigger: 'hover' }" style="width:100%;"></el-cascader>
          <!-- <span v-if="showTips" style="font-size:12px;color:red;">{{showMessage}}</span> -->
           <el-alert v-if="showTips" :closable="false" type="warning" show-icon>{{showMessage}}</el-alert>
        </el-form-item>
        <el-form-item label="房屋详细地址" prop="addressDetail" :rules="{required: false,message: '请输入房产详细地址',trigger: 'blur'}">
          <el-input type="textarea" rows="4"  v-model="dataForm.addressDetail"/>
        </el-form-item>
        <el-form-item label="小区名称" prop="villageName" :rules="{required: false,message: '请输入小区名称',trigger: 'blur'}">
          <el-input v-model="dataForm.villageName"/>
        </el-form-item>
        <el-form-item label="楼幢号" prop="buildNo" :rules="{required: false,message: '请输入楼幢号',trigger: 'blur'}">
          <el-input v-model="dataForm.buildNo"> <template slot="append">号</template></el-input>
        </el-form-item>
        <el-form-item label="不动产单元号" prop="unitNumber"  :rules="{required: false,message: '请输入不动产单元号',trigger: 'blur'}">
          <el-input v-model="dataForm.unitNumber" @change="handleSeachNumber"/>
          <!-- <span v-if="showError" style="font-size:12px;color:red;">该抵押物在系统中有拒件的记录，<a @click="rejectLook">前往查看></a></span> -->
          <el-alert v-if="showError" :closable="false" type="warning" show-icon>该抵押物在系统中有拒件的记录， <el-link @click="rejectLook" style="margin-top:-3px;" type="danger">前往查看</el-link></el-alert>
        </el-form-item>
        <el-form-item label="门牌号" prop="doorNo" :rules="{required: false,message: '请输入门牌号',trigger: 'blur'}">
          <el-input v-model="dataForm.doorNo"/>
        </el-form-item>
        <el-form-item label="抵押物现状" prop="currentSituation" :rules="{required: false,message: '请输入抵押物现状',trigger: 'change'}">
          <DicSelect dictType = "抵押物现状" :dictValue="dataForm.currentSituation" v-on:dictValue="dataForm.currentSituation = $event"/>
        </el-form-item>
         <el-form-item label="房龄" prop="houseAge" :rules="{required: false,message: '请输入房龄',trigger: 'blur'}">
         <el-input type="number" v-model="dataForm.houseAge"> <template slot="append">年</template></el-input>
        </el-form-item>
          <el-form-item label="产权人" prop="propertyOwner" :rules="{required: false,message: '请输入产权人',trigger: 'blur'}">
          <el-input  v-model="dataForm.propertyOwner"/>
        </el-form-item>
         <el-form-item label="土地权利性质" prop="landNature" :rules="{ required: false,message: '请选择土地权利性质',trigger: 'change'}">
          <DicSelect dictType = "土地权利性质" :dictValue="dataForm.landNature" v-on:dictValue="dataForm.landNature = $event"/>
        </el-form-item>
        <el-form-item
          label="权利(房产)性质"
          prop="houseNature"
          :rules="{ required: false,message: '请输入权利(房产)性质',trigger: 'change'}"
        >
          <el-input v-model="dataForm.houseNature" maxlength="10"/>
        </el-form-item>
        <el-form-item
          label="现使用情况"
          prop="nowUsage"
          :rules="{ required: false,message: '请选择现使用情况',trigger: 'change'}"
        >
           <DicSelect dictType = "现使用情况" 
           :dictValue="dataForm.nowUsage" 
           v-on:dictValue="dataForm.nowUsage = $event"/>
        </el-form-item>
         <el-form-item label="房屋用途" prop="houseUse" :rules="{ required: false,message: '请选择房屋用途',trigger: 'change'}">
         <DicSelect dictType = "房屋用途"  :dictValue="dataForm.houseUse" v-on:dictValue="dataForm.houseUse = $event"/>
        </el-form-item>
          <el-form-item label="土地使用期限" prop="durationLandUse" :rules="{required: false,message: '请输入土地使用期限',trigger: 'blur'}">
          <el-input  v-model="dataForm.durationLandUse"/>
        </el-form-item>
          <el-form-item label="建筑面积" prop="areaTotal" :rules="{required: false,message: '请输入建筑面积',trigger: 'blur'}">
          <el-input  v-model="dataForm.areaTotal"> <template slot="append">m²</template></el-input>
        </el-form-item>
          <el-form-item label="楼层数" prop="floors" :rules="{required: false,message: '请输入楼层数',trigger: 'blur'}">
          <el-input  v-model="dataForm.floors"> <template slot="append">层</template></el-input>
        </el-form-item>
          <el-form-item label="总楼层数" prop="floorsTotal" :rules="{required: false,message: '请输入总楼层数',trigger: 'blur'}">
          <el-input  v-model="dataForm.floorsTotal"> <template slot="append">层</template></el-input>
        </el-form-item>
          <el-form-item label="建筑类型" prop="houseType" :rules="{ required: false,message: '请选择建筑类型',trigger: 'change'}">
          <DicSelect dictType = "住宅类型"  :dictValue="dataForm.houseType" v-on:dictValue="dataForm.houseType = $event"/>
        </el-form-item>
          <el-form-item label="房屋朝向" prop="buildingHead">
           <DicSelect dictType = "房屋朝向"  :dictValue="dataForm.buildingHead" v-on:dictValue="dataForm.buildingHead = $event"/>
        </el-form-item>
         
         <el-form-item>
        
      </el-form-item>
      </el-form>
      


        <el-form :model="formData3"  ref="formData3" status-icon label-position="right" label-width="120px" style="width: 600px; margin-left:50px;" >
        
      <el-row
        v-for="(item,index) in formData3.powerAttrList"
        :key="item.key"  
        style="border-bottom: 1px solid #f0f0f0;padding: 10px;"
      >
         <el-form-item
          :label="item.borrowerTypeName"
          :prop="'powerAttrList.' + index + '.borrowerOrg'"
          
        >
          <el-input v-model="item.borrowerOrg" :placeholder="item.borrowerTypeName" />
        </el-form-item>
         <el-form-item
          label="借款金额"
          :prop="'powerAttrList.' + index + '.money'"
          
        >
        <!-- <template slot="append">万</template> -->
          <el-input v-model="item.money" placeholder="请输入借款金额" > </el-input>
        </el-form-item>
         <el-form-item
          label="期限"
          :prop="'powerAttrList.' + index + '.deadline'"
         
        >
          <el-input type="textarea" rows="4"  v-model="item.deadline" placeholder="请输入期限" />
        </el-form-item>
         <el-form-item
          label="剩余本金"
          :prop="'powerAttrList.' + index + '.remainCapital'"
          
        >
          <el-input type="number" v-model="item.remainCapital" placeholder="请输入剩余本金" />
        </el-form-item>
        <el-form-item
          label="还款方式"
          :prop="'powerAttrList.' + index + '.repayWay'"
          
        >
          <el-input v-model="item.repayWay" autocomplete="off" placeholder="请输入还款方式" />
        </el-form-item>

      </el-row>
    
        <el-form-item style="margin-top:30px;">
        <el-button  type="warning" v-if="defaultChangeValue === 'detail'" @click="createData" style="width:150px;height:40px;">保存</el-button>   
        <div v-else>
          <el-button  type="primary" @click="createHouseDraft(1)" style="width:150px;height:40px;">上一步</el-button>
          <el-button  type="warning" @click="createData(2)" style="width:150px;height:40px;">下一步</el-button>
        </div>
        </el-form-item>
    </el-form>

    </el-card>
  </div>
</template>

<style>
</style>

<script>
import { createHouse,createHouseDraft,updateHouse,findByProjectId } from '@/api/house'
import { listRegion,detailByAreaId } from '@/api/region'
import { findUnitNumber } from '@/api/reject'
import DicSelect from '@/components/select'

export default {
  name: 'house',
  components: { DicSelect },
  // 接受父组件的值
  props: {
     changeValue: undefined,
     projectId: undefined,
     operation: undefined
    },
  data() {
    return {
      defaultChangeValue: this.changeValue,
      appointNextTime:undefined,
      updateParam: undefined,
      list: undefined,
      total: 0,
      listLoading: true,
      stepType: undefined,
      defaultProjectId: undefined,
      showError: false,
      regionList:[],
      regionValues: [],
      showTips: false,
      showMessage: undefined,
      listQuery: {
        page: 1,
        limit: 20,
        pid: undefined,
        categoryName: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        purpose: undefined,
        ownedSituation: undefined,
        accessType: undefined,
        houseAddress: undefined,
        villageName: undefined,
        buildNo: undefined,
        unitNumber: undefined,
        doorNo: undefined,
        currentSituation: undefined,
        houseAge: undefined,
        landNature: undefined,
        houseUse: undefined,
        landUse: undefined,
        durationLandUse: undefined,
        areaTotal: undefined,
        floors: undefined,
        floorsTotal: undefined,
        licenseNo: undefined,
        buildingHead: undefined,
        houseType: undefined,
        projectId: undefined,
        houseHistries:[],
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        houseNature:undefined,
        nowUsage:undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      data: [{
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '姓名', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
       formData3: {
        powerAttrList: [
          {
            borrowerOrg: undefined,
            money: undefined,
            deadline: undefined,
            remainCapital: undefined,
            repayWay: undefined,
            borroweType: 1,
            borrowerTypeName: "一押借款机构",
          },
          {
            borrowerOrg: undefined,
            money: undefined,
            deadline: undefined,
            remainCapital: undefined,
            repayWay: undefined,
            borroweType: 2,
            borrowerTypeName: "二押借款机构",
          },
          {
            borrowerOrg: undefined,
            borrowerOrgType:undefined,
            money: undefined,
            deadline: undefined,
            remainCapital: undefined,
            repayWay: undefined,
            borroweType: 3,
            borrowerTypeName: '三押借款机构',
            loanType: undefined,
          },
        ]
      },
    }
  },
  watch: {
    "changeValue":function(val){
      this.defaultChangeValue = val
    }
  },
  computed: {
  },
  created() {
    console.log(this.defaultChangeValue)
    var form = localStorage.getItem("house")
    if(form!= undefined){
      this.dataForm = JSON.parse(form)
      if(this.dataForm.houseHistries != undefined) {
        this.formData3.powerAttrList = this.dataForm.houseHistries
      }
    }
    var localProjectId = localStorage.getItem("projectId")
  
  
    //回填 
    if( localProjectId != 'undefined') {
      console.log("回填")
      this.defaultProjectId = localProjectId
      this.findByProjectId()
    }

    //编辑
    if(this.projectId != undefined ) {
      console.log("编辑")
      this.defaultProjectId = this.projectId
      this.findByProjectId()
      this.defaultChangeValue = "detail"
    }
     
    this.getRegionList()

  },
  methods: {
    findByProjectId() {
      this.listLoading = true
      findByProjectId({projectId:this.defaultProjectId})
        .then(response => {
          if(response.data != undefined ) {
            this.dataForm = response.data[0]
            this.regionValues = []
            if(this.dataForm.houseHistries!=undefined){
               var data = this.dataForm.houseHistries
            for( let i=0 ; i < data.length;i++){
              data[i].borrowerTypeName = this.getValue(i+1)+"押借款机构"
            }
            this.formData3.powerAttrList = data
            }
            this.regionValues.push(this.dataForm.provinceId)
            this.regionValues.push(this.dataForm.cityId)
            this.regionValues.push(this.dataForm.areaId)
            console.log(this.dataForm)
            localStorage.setItem("requestMethod","edit")
          }
        })
        .catch(() => {
          this.resetForm()
        })
    },
   getRegionList() {
      listRegion()
        .then(response => {
          if(response.data != undefined ) {
            this.regionList = response.data
            
          }
        })
        .catch(() => {
        })
    },
    handleSeachNumber(){
      if( this.dataForm.unitNumber === undefined ) {
        this.showError = false
        return false
      }
      findUnitNumber({unitNumber: this.dataForm.unitNumber})
        .then(response => {
          if(response.data != undefined ) {
            if( response.data == 1) {
              this.showError = true
            }else{
              this.showError = false
            }
            
          }
        })
        .catch(() => {
        })
    },
    rejectLook(){
      this.$router.push("/task/rejectList")
    },
    handleChangeRegion(val){
       console.log(val)
       if( val==undefined || val.length==0){
       this.dataForm.provinceId = ""
       this.dataForm.cityId = ""
       this.dataForm.areaId = ""
         return false
       }
       this.dataForm.provinceId = val[0]
       this.dataForm.cityId = val[1]
       this.dataForm.areaId = val[2]
        detailByAreaId({areaId: val.lastItem})
        .then(response => {
            let areaName = response.data
            if("松江区" === areaName || "青浦区" === areaName) {
               this.showTips = true
               this.showMessage = "只做一押"
               return false
            }
            if("金山区" === areaName || "奉贤区" === areaName || "崇明县" === areaName) {
              this.showTips = true
              this.showMessage = "不符合产品大纲"
               return false
            }
            this.showTips = false
            this.showMessage = undefined
            
        })
        .catch(() => {
        })

    },
    getValue(val){
      if(val === 1) {
        return "一";
      }
      if(val == 2) {
        return "二";
      }
      if(val == 3) {
        return "三";
      }
    },
    resetForm() {
      this.dataForm = {
        purpose: undefined,
        ownedSituation: undefined,
        accessType: undefined,
        houseAddress: undefined,
        villageName: undefined,
        buildNo: undefined,
        unitNumber: undefined,
        doorNo: undefined,
        currentSituation: undefined,
        houseAge: undefined,
        landNature: undefined,
        houseUse: undefined,
        landUse: undefined,
        durationLandUse: undefined,
        areaTotal: undefined,
        floors: undefined,
        floorsTotal: undefined,
        licenseNo: undefined,
        buildingHead: undefined,
        houseType: undefined,
        projectId: undefined,
        houseHistries:[],
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined
      }
    },
    backStep(){
      this.$emit("stepChanged",3)
    },
    createData(val) {
      console.log(this.projectId)
      this.stepType = val
      this.dataForm.houseHistries = this.formData3.powerAttrList
      this.dataForm.projectId = this.defaultProjectId
      console.log(this.dataForm)
      // localStorage.setItem("house",JSON.stringify(this.dataForm))
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
              
               this.$refs['formData3'].validate(valid => {
              if (valid) {
                     console.log(this.defaultProjectId)
                     var requestMethod = localStorage.getItem("requestMethod")
                     if( this.operation === 'add') {
                       this.createHouse()
                     }else{
                       this.updateHouse()
                     }
                      

                    }
                  })

        }
      })
      
    },
    createHouse(){
           createHouse(this.dataForm)
            .then(response => {
                
                  this.$notify.success({
                   title: '成功',
                  message: '保存成功'
                  })
                  if( this.defaultChangeValue != 'detail' ) {
                        this.$emit("stepChanged",this.stepType === 1 ? 3 : 5)
                      }
                 })
                 .catch(response => {
              })
    },
    createHouseDraft(val){
      this.stepType = val
      this.dataForm.houseHistries = this.formData3.powerAttrList
      this.dataForm.projectId = this.defaultProjectId
           createHouseDraft(this.dataForm)
            .then(response => {
                  this.$notify.success({
                   title: '成功',
                  message: '草稿保存成功'
                  })
                  if( val === 2) {
                    this.$router.push("/project/index")
                  }else{
                      if( this.defaultChangeValue != 'detail' ) {
                        this.$emit("stepChanged",this.stepType === 1 ? 3 : 5)
                      }
                  }
                 })
                 .catch(response => {
              })
    },
    updateHouse(){
           updateHouse(this.dataForm)
            .then(response => {
                
                  this.$notify.success({
                   title: '成功',
                  message: '保存成功'
                  })
                  if( this.defaultChangeValue != 'detail' ) {
                        this.$emit("stepChanged",this.stepType === 1 ? 3 : 5)
                  }
                 })
                 .catch(response => {
              })
    },
    vailInput(type){
      var reg = /[\(]/g,reg2 = /[\)]/g,reg3 = /\s*/g;
      this.dataForm[type] = this.dataForm[type].toUpperCase();
      this.dataForm[type] = this.dataForm[type].replace(reg,"（").replace(reg2,"）").replace(reg3,"");
    }
  }
}
</script>
